package json;

import cn.hutool.json.JSONUtil;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: JSONTest01
 * Package: json
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/8/21 11:21
 * @Version 1.0
 */
public class JSONTest01 {
    /*将一个java对象转换成JSON格式*/
     @Test
    public void testObjectToJson() {
         Student student = new Student(2002, "张三", "男", 20);
         String jsonStr = JSONUtil.toJsonStr(student);
         System.out.println(jsonStr); //{"sno":2002,"name":"张三","gender":"男","age":20}
     }
    /*将JSON字符串转换成Java对象*/
     @Test
    public void testJsonToObject() {
         String jsonStr = "{\"sno\":2002,\"name\":\"张三\",\"gender\":\"男\",\"age\":20}";
         Student student = JSONUtil.toBean(jsonStr, Student.class);
         System.out.println(student);
     }
    /*将一个集合转换成json*/
    @Test
    public void testListToJson() {
        List<Student> students = Arrays.asList(
                new Student(2002, "张三", "男", 20),
                new Student(2004, "李四", "女", 23)
        );
        System.out.println(JSONUtil.toJsonStr(students));
        System.out.println(JSONUtil.toJsonPrettyStr(students));
    }
    /*将一个json转换成集合*/
    @Test
    public void testJsonToList() {
        String jsonStr = "[{\"sno\":2002,\"name\":\"张三\",\"gender\":\"男\",\"age\":20},{\"sno\":2004,\"name\":\"李四\",\"gender\":\"女\",\"age\":23}]";
        JSONUtil.parseArray(jsonStr).toList(Student.class).forEach(System.out::println);
    }
    /*将map转换成json串*/
    @Test
    public void testMapToJson() {
        List<Student> students = Arrays.asList(
                new Student(2002, "张三", "男", 20),
                new Student(2004, "李四", "女", 23)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + "", stu -> stu));
        System.out.println(JSONUtil.toJsonStr(map));
        System.out.println(JSONUtil.toJsonPrettyStr(map));
    }

}
